import ast
import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
import requests
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.classapi.models import Class
from apps.classapi.serializers.user import ClassSerializer
from apps.tally.models import Tally
from apps.user.models import User
from utils.bases64 import main


class ApiClass(APIView):
    """创建添加被记账用户"""

    def get(self, request):
        # 获取用户并返回
        uid = request.GET.get("uid")  # 获取用户的id
        # 查询用户是否存在并且进行判断
        user = User.objects.filter(id=uid)
        if not user:
            ret = {
                "uid": 0,
                "data": "用户不存在，请重新登录！"
            }
            return JsonResponse(ret)
        # 查询被记账的用户的信息
        aclass = Class.objects.filter(user=uid)
        # 对查询到的信息进行处理
        data = []
        for i in aclass:
            money = 0
            tally = Tally.objects.filter(user=uid, aclass=i.id)
            count = len(tally)
            for t in tally:
                print(t.kind, type(t.kind))
                print(t.money, type(t.money))
                if t.kind == "1":
                    money = money + t.money
                elif t.kind == "2":
                    money = money - t.money
            print(money)
            aclasses = {
                "id": i.id,
                'name': i.name,
                "count": count, "money": money
            }
            data.append(aclasses)
        ret = {'uid': uid, "data": data}
        return JsonResponse(ret)

    def post(self, request):
        # 对被添加的用户进行怎删改查
        # 接受参数
        data = request.POST.get("data")
        types = request.POST.get("type")
        data1 = main(data)  # 将接受到的base64格式代码转化成python
        datas = ast.literal_eval(data1)  # 将接受到的数据转化成json格式
        if types == "add":
            # 添加用户
            print("123")
            user = User.objects.get(id=datas["ufid"])
            # print(user)
            datass = {
                "name": datas["classname"],
                'user': user.id
            }
            # 反序列化-数据校验
            serializer = ClassSerializer(data=datass)
            serializer.is_valid(raise_exception=True)
            # 反序列化-数据保存
            serializer.save()
            # print("+"*20,serializer.data)
            ret = {"uid": user.id, "data": ["true", "删除成功!"]}
            return Response(ret)
        elif types == "edit":
            print("123456")
            user = User.objects.get(id=datas["ufid"])
            # print(user)
            datass = {
                "name": datas["classname"],
                'user': user.id,
                'id': datas["classid"]
            }
            try:  # 判断被修改的记账用户是否存在
                aclass = Class.objects.get(id=datas["classid"])
            except Class.DoesNotExist:
                ret = {"uid": 0, "data": ["false", "修改失败!"]}
                return JsonResponse(ret)
            # 反序列化-数据校验
            serializer = ClassSerializer(aclass, data=datass)
            serializer.is_valid(raise_exception=True)
            # 反序列化-数据保存(save内部会调用序列化器类的update方法)
            serializer.save()

            ret = {"uid": user.id, "data": ["true", "修改成功!"]}
            return Response(ret)
        elif types == "del":
            print("123789")
            # print(type(datas))
            id = datas["classid"]
            # print(id)
            try:
                aclass = Class.objects.filter(id=id)
            except Class.DoesNotExist:
                ret = {"uid": 0, "data": ["false", "删除失败!"]}
                return JsonResponse(ret)
            uid = aclass[0].user.id
            aclass.delete()
            ret = {"uid": uid, "data": ["true", "删除成功!"]}
            return Response(ret)
